package _08使用Constructor创建对象;

import com.asin.domain.Person;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Demo {
    public static void main(String[] args) throws Exception {

        test3();
    }

    //获取无参构造方法创建对象(public权限)
    public static void test1() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<Person> personClass = Person.class;
        Constructor<Person> constructor = personClass.getConstructor();
        Person person = constructor.newInstance();
        System.out.println(person);
    }
    //获取有参构造方法创建对象(public权限)
    public static void test2() throws Exception {
        Class<?> aClass = Class.forName("com.asin.domain.Person");
        Constructor<?> constructor = aClass.getConstructor(String.class, int.class);
        Person person =(Person) constructor.newInstance("张三", 23);
        System.out.println(person);
    }

    //获取私有带参构造方法创建对象(私有权限)
    public static void test3() throws Exception {
        Class<?> aClass = Class.forName("com.asin.domain.Person");
        Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class);
        declaredConstructor.setAccessible(true);//暴力反射，开启权限创建对象
        Object o = declaredConstructor.newInstance("柳岩");
        System.out.println(o);

    }
}
